package com.hll.api.controller.kaola;

import com.alibaba.fastjson.JSONObject;
import com.hll.api.config.web.RespMessage;
import com.hll.api.entity.User;
import com.hll.api.service.MailService;
import com.hll.api.service.UserService;
import com.hll.api.service.impl.RedisTemplateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author 何龙
 * @create 2019-06-23 19:41
 */
@RestController
@RequestMapping("/api/kaola")
public class LoginController {

    private final
    MailService service;
    private final
    UserService userService;
    private final
    RedisTemplateService redisTemplateService;
    private static final String SESSION_CODE = "kaolaCode";
    private static final String SESSION_USER = "user";
    private static final String TOKEN_USER = "userToken";

    @Autowired
    public LoginController(MailService service, UserService userService, RedisTemplateService redisTemplateService) {
        this.service = service;
        this.userService = userService;
        this.redisTemplateService = redisTemplateService;
    }

    /**
     * @api {post} /api/kaola/send/mail 发送邮箱验证码
     * @apiVersion 1.0.0
     * @apiName sendMail
     * @apiGroup kaola
     * @apiParam {int} email 邮箱
     * @apiParamExample {string} 请求示例:
     * email=123456@qq.com
     * @apiSuccess {Number} status 状态码,0为接口访问成功
     * @apiSuccess {String} err 错误信息
     * @apiSuccess {Object} datas 成功时返回考拉接口数据
     */
    @PostMapping("/send/mail")
    public RespMessage sendMail(String email, HttpSession session) {
        if (email == null) {
            return RespMessage.error( "邮箱不能为空" );
        }
        String regEx1 = "^([a-z0-9A-Z]+[-|.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
        Pattern p = Pattern.compile( regEx1 );
        Matcher m = p.matcher( email );
        if (m.matches()) {
            String code = service.send( email );
            Map<String, String> map = new HashMap<>();
            map.put( "email", email );
            map.put( "code", code );
            String s = SESSION_CODE + session.getId();
            redisTemplateService.set( s, map );
            return RespMessage.success( s );
        } else {
            return RespMessage.error( "邮箱格式不正确" );
        }
    }

    /**
     * @api {post} /api/kaola/register 邮箱注册
     * @apiVersion 1.0.0
     * @apiName register
     * @apiGroup kaola
     * @apiParam {string} pass 密码
     * @apiParam {string} code 邮箱验证码
     * @apiParam {string} sessionId 邮件发送成功时的id
     * @apiParamExample {string} 请求示例:
     * pass=1234&code=asdasd
     * @apiSuccess {Number} status 状态码,0为接口访问成功
     * @apiSuccess {String} err 错误信息
     * @apiSuccess {Object} datas 成功时返回考拉接口数据
     */
    @PostMapping("/register")
    public RespMessage register(String pass, String code, String sessionId) {
        if (pass == null || code == null || sessionId == null) {
            return RespMessage.error( "参数不完整" );
        }
        Map map = redisTemplateService.get( sessionId, Map.class );
        if (map == null) {
            return RespMessage.error( "未发送验证码" );
        }
        if (map.get( "code" ) == null) {
            return RespMessage.error( "未发送验证码" );
        } else if (!map.get( "code" ).equals( code )) {
            return RespMessage.error( "验证码不正确" );
        }
        User name = userService.getName( (String) map.get( "email" ) );
        if (name != null) {
            return RespMessage.error( "邮箱已被注册" );
        }
        User user = new User();
        user.setEmail( (String) map.get( "email" ) );
        user.setPass( pass );
        user.setImg( "https://haitao.nosdn2.127.net/vtgcByWTZlKwtnRQvhvLT170102401020_150_150.png" );
        userService.save( user );
        redisTemplateService.set( sessionId, null );
        return RespMessage.success( "注册成功" );

    }

    /**
     * @api {post} /api/kaola/login 登录
     * @apiVersion 1.0.0
     * @apiName login
     * @apiGroup kaola
     * @apiParam {string} pass 密码
     * @apiParam {string} email 邮箱
     * @apiParamExample {string} 请求示例:
     * pass=1234&email=123456@qq.com
     * @apiSuccess {Number} status 状态码,0为接口访问成功
     * @apiSuccess {String} err 错误信息
     * @apiSuccess {Object} datas 成功时返回考拉接口数据
     */
    @PostMapping("/login")
    public RespMessage login(String email, String pass, HttpSession session) {
        if (pass == null || email == null) {
            return RespMessage.error( "参数不完整" );
        }
        User user = userService.getName( email );
        if (user == null) {
            return RespMessage.error( "用户名或密码不正确" );
        }
        if (!user.getPass().equals( pass )) {
            return RespMessage.error( "用户名或密码不正确" );
        } else {
            String key = SESSION_USER + session.getId();
            redisTemplateService.set( key, user );
            JSONObject object = new JSONObject();
            object.put( "userToken", key );
            return RespMessage.success( object, "登录成功" );
        }

    }

    /**
     * @api {post} /api/kaola/logout 退出登录
     * @apiVersion 1.0.0
     * @apiName logout
     * @apiGroup kaolat
     * @apiHeader {String} userToken 用户授权登录token
     */
    @PostMapping("/logout")
    public RespMessage logout(HttpServletRequest request) {
        String header = request.getHeader( TOKEN_USER );
        redisTemplateService.set( header, "123" );
        return RespMessage.success( "退出成功！" );
    }

    /**
     * @api {get} /api/kaola/get/user 获取当前登录的用户
     * @apiVersion 1.0.0
     * @apiName getuser
     * @apiGroup kaola
     * @apiHeader {String} userToken 用户授权登录token
     * @apiSuccess {Number} status 状态码,0为接口访问成功
     * @apiSuccess {String} err 错误信息
     * @apiSuccess {Object} datas 成功时返回考拉接口数据
     */
    @GetMapping("/get/user")
    public RespMessage get(HttpServletRequest request) {
        User user = userService.getUser( request );
        if (user == null) {
            return RespMessage.loginError();
        }
        return RespMessage.success( user, "成功" );
    }

}
